import React, { Component } from 'react'
import axios from 'axios';
import PubSub from 'pubsub-js';

export default class HeroList extends Component {
    state = {
        heros: []
    }

    //渲染组件
    render() {
        return (
            <div className="hero-list">
                {
                    this.state.heros.map(item => {
                        return <div key={item.id} className="item">
                                    <img src={"http://cdn.xiaohigh.com" + item.image} alt="" />
                                    <p>{item.name}</p>
                                </div>
                    })
                }
            </div>
        )
    }

    async componentDidMount(){
        //发送 AJAX 请求
        let result = await axios('http://api.xiaohigh.com/heros');

        this.setState({
            heros: result.data
        });

        //设置消息的订阅
        PubSub.subscribe('keywords', async (_, data) => {
            // console.log('关键字为: ', data);
            let result = await axios('http://api.xiaohigh.com/heros', {
                params: {
                    name_like: data
                }
            });

            //设置新的英雄列表
            this.setState({
                heros: result.data
            })
        });
    }

    componentWillUnmount(){
        //收尾工作
        //取消订阅
        PubSub.unsubscribe('keywords');
    }


}
